import requests
from bs4 import BeautifulSoup
import re
def get_walmart_upc(product_url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Accept-Language": "en-US,en;q=0.9",
        "Referer": "https://www.walmart.ca/",
        "authority": "www.walmart.ca"
    }
    
    try:
        response = requests.get(product_url, headers=headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # 定位包含UPC的表格行
            upc_row = soup.find('td', string=re.compile(r'Universal Product Code \(UPC check\)'))
            if upc_row:
                upc_value = upc_row.find_next_sibling('td').text.strip()
                return upc_value
            return None
        else:
            print(f"请求失败，状态码：{response.status_code}")
            return None
    except Exception as e:
        print(f"发生错误：{str(e)}")
        return None

# 使用示例
if __name__ == "__main__":
    product_url = "https://www.walmart.ca/en/ip/New-Bright-1-18-Scale-Polaris-Angry-RZR-Radio-Control-Monster-ATV-61875U/6000205470779"
    upc = get_walmart_upc(product_url)
    print(f"商品UPC码：{upc}")